package pub.tbc.api.helper;

import lombok.extern.slf4j.Slf4j;
import pub.tbc.toolkit.core.classes.ClassUtil;
import pub.tbc.toolkit.core.collect.Lists;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author tbc on 2017/3/31 13:23:57.
 */
@Slf4j
public class ClassHelper {

    public static Class<?> load(String className) {
        return ClassUtil.loadClass(className);
    }

    public static List<Class<?>> load(List<String> classNames) {
        return classNames.stream().map(ClassHelper::load).collect(Collectors.toList());
    }

    public static Object instance(Class<?> clazz) {
        try {
            return clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static List<Object> instance(List<Class<?>> classes) {
        return classes.stream().map(ClassHelper::instance).collect(Collectors.toList());
    }

    public static <T> T genericInstance(Class<T> clazz) {
        try {
            return clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static <T> List<T> genericInstance(List<Class<T>> classes) {
        return classes.stream().map(ClassHelper::genericInstance).collect(Collectors.toList());
    }

    public static <T> Class<T> loadClass(String className) {
        Class<?> clazz = ClassUtil.loadClass(className);
        return (Class<T>) clazz;
    }

    public static <T> List<Class<T>> loadClass(List<String> classNames) {
        List<Class<T>> tt = Lists.newArrayList();
        classNames.forEach(className -> tt.add(loadClass(className)));
        return tt;
    }
}
